package net.ib.mtalk.network.task;

import java.util.UUID;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.RemoveMembersReq;
import net.ib.mntalk.protocol.Session.RemoveMembersRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.DatabaseContract.ViewTable;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class RemoveMembersTask  extends AsyncNetTask {
	
	private RemoveMembersReq mRemoveMembersReq;
	private int mLeaveChat;
	private UUID mClientViewUuid;
	
	public RemoveMembersTask(Context context, Handler handler, RemoveMembersReq removeMembersReq, UUID clienViewUuid, int leaveChat){
		super(context, handler);
		this.mRemoveMembersReq = removeMembersReq;
		this.mLeaveChat = leaveChat;
		this.mClientViewUuid = clienViewUuid;
	}
	
	public RemoveMembersTask(Context context, Handler handler, RemoveMembersReq removeMembersReq){
		this(context, handler, removeMembersReq, null, 0);
	}
	
	@Override
	protected TcpEnvelope onPreExecute() {
		
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mRemoveMembersReq)
			.setMethodId(Session.View.RemoveMembers)
			.build();
		return rev;
	}
	
	@Override
	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.d("RemoveMembersTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		RemoveMembersRes removeMembersRes = (RemoveMembersRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("RemoveMembersTask ResponseCode : " + removeMembersRes.getResponseCode());
		
		if(removeMembersRes.getResponseCode() == Common.SUCCESS){
			// TODO : 디비작업
			Log.i("ATOM", "RemoveMembersTask : " + mLeaveChat);
			if(mLeaveChat == ViewTable.EnableType.LEAVE.ordinal() && mClientViewUuid != null){
				InboxDatabaseHelper.updateViewEnable(mContext,  mClientViewUuid.getMostSignificantBits(), 
						mClientViewUuid.getLeastSignificantBits(), ViewTable.EnableType.LEAVE.ordinal());
			}
			
//			InboxDatabaseHelper.updateView(mQueryHandler, viewInfo);
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_REMOVE_MEMBERS_SUCCESS));
		} else{
			// TODO : 디비작업
//			InboxDatabaseHelper.updateView(mQueryHandler, viewInfo);

			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_REMOVE_MEMBERS_FAIL));
		}
	}
}